package com.xianyuwangyou.taizhangdengji

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.AlertDialog
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountEditScreen(
    record: AccountRecord,
    onNavigateBack: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 获取配置数据管理器实例
    val configDataManager = ConfigDataManager.getInstance()
    val dataManager = AccountDataManager.getInstance()
    val context = LocalContext.current
    
    // 获取营销员和产品列表
    val marketers = configDataManager.getMarketers()
    val products = configDataManager.getProducts()
    
    var marketer by remember { mutableStateOf(record.marketer) }
    var product by remember { mutableStateOf(record.product) }
    var secondaryProduct by remember { mutableStateOf(record.secondaryProduct) } // 二级产品名称
    var amount by remember { mutableStateOf(record.amount.toString()) }
    var date by remember { mutableStateOf(record.date) }
    var notes by remember { mutableStateOf(record.notes) }
    
    var isMarketerMenuExpanded by remember { mutableStateOf(false) }
    var isProductMenuExpanded by remember { mutableStateOf(false) }
    var showDeleteConfirmDialog by remember { mutableStateOf(false) }
    
    Scaffold(
        modifier = modifier.fillMaxSize(),
        topBar = {
            TopAppBar(
                title = { Text("修改台账") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(Color(0xFFF5F5F5)) // 添加灰色背景
                .padding(16.dp)
        ) {
            // 白色背景卡片
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    // 营销员下拉菜单
                    ExposedDropdownMenuBox(
                        expanded = isMarketerMenuExpanded,
                        onExpandedChange = { isMarketerMenuExpanded = it }
                    ) {
                        TextField(
                            readOnly = true,
                            value = marketer,
                            onValueChange = { },
                            label = { Text("营销员") },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isMarketerMenuExpanded) },
                            modifier = Modifier
                                .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                        ExposedDropdownMenu(
                            expanded = isMarketerMenuExpanded,
                            onDismissRequest = { isMarketerMenuExpanded = false },
                            containerColor = Color.White // 设置下拉菜单背景为白色
                        ) {
                            marketers.forEach { item ->
                                Text(
                                    text = item,
                                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 16.dp, vertical = 8.dp)
                                        .clickable { 
                                            marketer = item
                                            isMarketerMenuExpanded = false
                                        }
                                )
                            }
                        }
                    }
                    
                    // 产品名称下拉菜单
                    ExposedDropdownMenuBox(
                        expanded = isProductMenuExpanded,
                        onExpandedChange = { isProductMenuExpanded = it }
                    ) {
                        TextField(
                            readOnly = true,
                            value = product,
                            onValueChange = { },
                            label = { Text("产品名称") },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isProductMenuExpanded) },
                            modifier = Modifier
                                .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                        ExposedDropdownMenu(
                            expanded = isProductMenuExpanded,
                            onDismissRequest = { isProductMenuExpanded = false },
                            containerColor = Color.White // 设置下拉菜单背景为白色
                        ) {
                            products.forEach { item ->
                                Text(
                                    text = item,
                                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 16.dp, vertical = 8.dp)
                                        .clickable { 
                                            product = item
                                            isProductMenuExpanded = false
                                        }
                                )
                            }
                        }
                    }
                    
                    // 添加二级产品名称下拉菜单
                    var isSecondaryProductMenuExpanded by remember { mutableStateOf(false) }
                    val secondaryProducts = configDataManager.getSecondaryProducts(product)
                    
                    ExposedDropdownMenuBox(
                        expanded = isSecondaryProductMenuExpanded,
                        onExpandedChange = { isSecondaryProductMenuExpanded = it }
                    ) {
                        TextField(
                            readOnly = true,
                            value = secondaryProduct,
                            onValueChange = { },
                            label = { Text("二级产品名称") },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isSecondaryProductMenuExpanded) },
                            modifier = Modifier
                                .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                        ExposedDropdownMenu(
                            expanded = isSecondaryProductMenuExpanded,
                            onDismissRequest = { isSecondaryProductMenuExpanded = false },
                            containerColor = Color.White // 设置下拉菜单背景为白色
                        ) {
                            secondaryProducts.forEach { item ->
                                Text(
                                    text = item,
                                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 16.dp, vertical = 8.dp)
                                        .clickable { 
                                            secondaryProduct = item
                                            isSecondaryProductMenuExpanded = false
                                        }
                                )
                            }
                        }
                    }
                    
                    TextField(
                        value = amount,
                        onValueChange = { amount = it },
                        label = { Text("数量") },
                        modifier = Modifier
                            .fillMaxWidth(),
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color.Transparent,
                            unfocusedContainerColor = Color.Transparent,
                            disabledContainerColor = Color.Transparent
                        )
                    )
                    
                    // 添加单位输入框
                    /*
                    TextField(
                        value = unit,
                        onValueChange = { unit = it },
                        label = { Text("单位") },
                        modifier = Modifier
                            .fillMaxWidth(),
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color.Transparent,
                            unfocusedContainerColor = Color.Transparent,
                            disabledContainerColor = Color.Transparent
                    )
                    */
                    
                    TextField(
                        value = notes,
                        onValueChange = { notes = it },
                        label = { Text("备注") },
                        modifier = Modifier
                            .fillMaxWidth(),
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color.Transparent,
                            unfocusedContainerColor = Color.Transparent,
                            disabledContainerColor = Color.Transparent
                        )
                    )
                }
            }
            
            // 按钮行
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                // 删除按钮
                Button(
                    onClick = { showDeleteConfirmDialog = true },
                    modifier = Modifier
                        .weight(1f)
                        .padding(end = 8.dp),
                    colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                        containerColor = Color.Red // 红色背景表示删除操作
                    )
                ) {
                    Icon(
                        imageVector = Icons.Filled.Delete,
                        contentDescription = "删除",
                        tint = Color.White,
                        modifier = Modifier.padding(end = 8.dp)
                    )
                    Text("删除", color = Color.White)
                }
                
                // 保存按钮
                Button(
                    onClick = {
                        // 保存台账记录的逻辑
                        try {
                            // 验证输入
                            if (amount.isBlank()) {
                                Toast.makeText(context, "请输入数量", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            val amountValue = amount.toIntOrNull()
                            if (amountValue == null) {
                                Toast.makeText(context, "请输入有效的数量", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            if (marketer.isBlank() || product.isBlank()) {
                                Toast.makeText(context, "请选择营销员和产品", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            // 创建更新后的台账记录
                            val updatedRecord = AccountRecord(
                                id = record.id, // 保持原有ID
                                marketer = marketer,
                                product = product,
                                secondaryProduct = secondaryProduct, // 二级产品名称
                                amount = amountValue,
                                date = date,
                                notes = notes
                            )
                            
                            // 更新记录
                            dataManager.updateAccountRecordAndSave(updatedRecord, context)
                            
                            // 显示成功消息
                            Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show()
                            
                            // 返回上一页
                            onNavigateBack()
                        } catch (e: Exception) {
                            Toast.makeText(context, "更新失败: ${e.message}", Toast.LENGTH_SHORT).show()
                            e.printStackTrace()
                        }
                    },
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 8.dp),
                    colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF019883) // 修改为指定颜色
                    )
                ) {
                    Text("保存")
                }
            }
            
            // 删除确认对话框
            if (showDeleteConfirmDialog) {
                AlertDialog(
                    onDismissRequest = { showDeleteConfirmDialog = false },
                    title = { Text("确认删除") },
                    text = { Text("确定要删除这条台账记录吗？") },
                    confirmButton = {
                        Button(
                            onClick = {
                                // 执行删除操作
                                dataManager.deleteAccountRecordAndSave(record.id, context)
                                
                                // 显示删除成功消息
                                Toast.makeText(context, "记录已删除", Toast.LENGTH_SHORT).show()
                                
                                // 关闭对话框
                                showDeleteConfirmDialog = false
                                
                                // 返回上一页
                                onNavigateBack()
                            },
                            colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                                containerColor = Color.Transparent
                            )
                        ) {
                            Text("确认删除", color = Color.Red)
                        }
                    },
                    dismissButton = {
                        Button(
                            onClick = { showDeleteConfirmDialog = false },
                            colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                                containerColor = Color.Transparent
                            )
                        ) {
                            Text("取消", color = Color.Black)
                        }
                    }
                )
            }
        }
    }
}